package upload;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//import com.google.appengine.api.blobstore.BlobInfo;
//import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class UploadAudio extends HttpServlet {
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		// request session variables
		HttpSession session = req.getSession(true);
		String username = (String) session.getAttribute("username");
		
		// get the blob key
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
        BlobKey blobKey = blobs.get("fileName");
		
        // add the entity data to the datastore
		Key audioFileKey = KeyFactory.createKey("AudioFiles", "mediaFiles");
		String mediaName = req.getParameter("mediaName");
		Entity file = new Entity("Audio", audioFileKey);
		try {
			AddBlobInfo(file, blobKey);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		AddEntityInfo(req, resp, file, username, mediaName, blobKey);
		
		// reload the page to show the changes
		String entityKey = KeyFactory.keyToString(file.getKey());
	    resp.sendRedirect("uploadComplete.jsp?entityKey="+entityKey);
		//resp.sendRedirect(req.getHeader("referer"));
	}
	
	public static void AddEntityInfo(HttpServletRequest req, HttpServletResponse resp, Entity _file, String _user, String _mediaName, BlobKey _blobKey) {
        
        _file.setProperty("blobKey", _blobKey);
        _file.setProperty("user", _user);
        if (_mediaName.length() > 18) {
        	String shortName = _mediaName.substring(0, 18); 
        	_file.setProperty("mediaName", shortName);
        } else {
        	_file.setProperty("mediaName", _mediaName);
        }
        
        // adding extra file details depending on media type
        String mediaType = (String) _file.getProperty("contentType");//blobInfo.getContentType().split("/")[0];
        if (mediaType.equals("audio")) {
        	AddAudioFile(_file, req.getParameter("artist"), req.getParameter("folder"), req.getParameter("audioGenre"));
        } else if (mediaType.equals("video")) {
        	AddVideoFile(_file, req.getParameter("videoGenre"), req.getParameter("year"), req.getParameter("folder"));
        } else if (mediaType.equals("image")) {
        	AddImageFile(_file, req.getParameter("folder"));
        } else if (mediaType.equals("application")) {
        	AddDocumentFile(_file, req.getParameter("folder"));
        }
        
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		datastore.put(_file);
	}
	
	public static void AddAudioFile(Entity audioFile, String _artist, String _audioAlbum, String _audioGenre) throws NullPointerException {
		try {
			if (_artist.equals("")) {
				audioFile.setProperty("artist", "Unknown");
			} else {
				audioFile.setProperty("artist", _artist);
			}
			if (_artist.equals("")) {
				audioFile.setProperty("album", "Unknown");
			} else {
				audioFile.setProperty("album", _audioAlbum);
			}
			if (_artist.equals("")) {
				audioFile.setProperty("genre", "Unknown");
			} else {
				audioFile.setProperty("genre", _audioGenre);
			}
		}
		catch (NullPointerException e) {
			audioFile.setProperty("artist", "Unknown");
			audioFile.setProperty("album", "Unknown");
			audioFile.setProperty("genre", "Unknown");
		}
	}
	
	public static void AddVideoFile(Entity videoFile, String _videoGenre, String _year, String _collection) throws NullPointerException {
		try {
			if (_videoGenre.equals("")) {
				videoFile.setProperty("genre", "Unknown");
			} else {
				videoFile.setProperty("genre", _videoGenre);
			}
			if (_year.equals("")) { 
				videoFile.setProperty("year", "Unknown");
			} else {
				videoFile.setProperty("year", _year);
			}
			if (_collection.equals("")) {
				videoFile.setProperty("collection", "Unknown");
			} else {
				videoFile.setProperty("collection", _collection);
			}
		}
		catch (NullPointerException e) {
			videoFile.setProperty("genre", "Unknown");
			videoFile.setProperty("year", "Unknown");
			videoFile.setProperty("collection", "Unknown");
		}
	}
	
	public static void AddImageFile(Entity imageFile, String _photoAlbum) throws NullPointerException {
		try {
			if (_photoAlbum.equals("")) {
				imageFile.setProperty("album", "Unknown");
			} else {
				imageFile.setProperty("album", _photoAlbum);
			}
		}
		catch (NullPointerException e) {
			imageFile.setProperty("album", "Unknown");
		}
	}
	
	public static void AddDocumentFile(Entity documentFile, String _documentAlbum) throws NullPointerException {
		try {
			if (_documentAlbum.equals("")) {
				documentFile.setProperty("album", "Unknown");
			} else {
				documentFile.setProperty("album", _documentAlbum);
			}
		}
		catch (NullPointerException e) {
			documentFile.setProperty("album", "Unknown");
		}
	}
	
	public static void AddBlobInfo(Entity _file, BlobKey _blobKey) throws ParseException {
		BlobInfoFactory blobInfoFactory = new BlobInfoFactory();
        BlobInfo blobInfo = blobInfoFactory.loadBlobInfo(_blobKey);
		// blob info
        _file.setProperty("fileName", blobInfo.getFilename());
        _file.setProperty("fileSize", blobInfo.getSize());
        String dateString = DateFormat.getDateInstance(DateFormat.MEDIUM).format(blobInfo.getCreation());
        //DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
        //Date date = df.parse(myString);
        _file.setProperty("dateCreated", dateString);
        _file.setProperty("contentType", blobInfo.getContentType().split("/")[0]);
	}
}
